using System;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using viBook.Common;

namespace viBook.Models
{
    public class CommentRepository : ICommentRepository
    {
        viBookContext context = new viBookContext();

        public IQueryable<ChapterComment> All
        {
            get { return context.Comments; }
        }

        IQueryable<ChapterComment> ICommentRepository.FetchCommentsByPage(int chapterId, int pageNo)
        {
            var comments = context.Comments.OrderByDescending(c => c.CreatedDate).Skip(Constant.MaximunCommentPerChapter * (pageNo - 1)).Take(Constant.MaximunCommentPerChapter);
            return comments;
        }

        public IQueryable<ChapterComment> AllIncluding(params Expression<Func<ChapterComment, object>>[] includeProperties)
        {
            IQueryable<ChapterComment> query = context.Comments;
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public ChapterComment Find(int id)
        {
            return context.Comments.Find(id);
        }

        public void InsertOrUpdate(ChapterComment chapterComment)
        {
            chapterComment.CreatedDate = DateTime.Now;
            if (chapterComment.Id == default(int))
            {
                // New entity
                context.Comments.Add(chapterComment);
            }
            else
            {
                // Existing entity
                context.Entry(chapterComment).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var comment = context.Comments.Find(id);
            context.Comments.Remove(comment);
        }

        public void Save()
        {
            context.SaveChanges();
        }
    }

    public interface ICommentRepository
    {
        IQueryable<ChapterComment> All { get; }
        IQueryable<ChapterComment> FetchCommentsByPage(int chapterId, int pageNo);
        IQueryable<ChapterComment> AllIncluding(params Expression<Func<ChapterComment, object>>[] includeProperties);
        ChapterComment Find(int id);
        void InsertOrUpdate(ChapterComment chapterComment);
        void Delete(int id);
        void Save();
    }
}